import { Component, OnInit } from '@angular/core';
import {DeptMngService} from './dept-mng.service';
import {StatusEnum} from '../../../core/enum/status.enum';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
declare var $: any;

@Component({
  selector: 'app-dept-mng',
  templateUrl: './dept-mng.component.html',
  styleUrls: ['./dept-mng.component.scss'],
  providers: [DeptMngService]
})
export class DeptMngComponent implements OnInit {
  treeGrid = null;
  tableConfig = {
    id: 'tableDept',
    renderTo: 'deptRef',
    headerAlign: 'left',
    headerHeight: '30',
    dataAlign: 'left',
    indentation: '20',
    folderOpenIcon: 'assets/tree-grid/open.png',
    folderCloseIcon: 'assets/tree-grid/close.png',
    hoverRowBackground: 'false',
    folderColumnIndex: '1',
    columns: [
      { headerText: '·', headerAlign: 'center', dataAlign: 'center', width: '1'},
      { headerText: '部门名称', dataField: 'title', headerAlign: 'left', dataAlign: 'left', width: '200'},
      { headerText: '部门负责人', dataField: 'leader', headerAlign: 'center', dataAlign: 'center', width: '200'},
      { headerText: '部门领导', dataField: 'leaderStr', headerAlign: 'center', dataAlign: 'center', width: '200'},
      { headerText: '部门电话', dataField: 'telphone', headerAlign: 'center', dataAlign: 'center', width: '200'},
      { headerText: '传真', dataField: 'fax', headerAlign: 'center', dataAlign: 'center', width: '200'},
      {
        headerText: '操作', headerAlign: 'center', dataAlign: 'center', width: '200',
        handler: ['编辑', '添加子机构', '删除']
        // handler: `
        //   <span id="editDeptRef" class="operaFont firOpera" title="编辑">编辑</span>
        //   <span id="addDeptOwnRef" class="operaFont firOpera" title="添加子机构">添加子机构</span>
        //   <span id="deleteDeptRef" class="operaFont">删除</span>`
      },
    ],
    data: [],
  };
  headTeacherList = [];
  departInfos: DepartInfo = new DepartInfo();
  isVisible = false;
  validateForm: FormGroup;
  listOfMapData = [];
  rootClear = true;
  placeholderText = '默认顶级部门';
  constructor(
    private http: DeptMngService,
    private fb: FormBuilder,
  ) { }

  ngOnInit() {
    this.pageList();
    this.initForm();
  }


  pageList() {
    this.http.getList({}).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.tableConfig.data = res.datas;
        this.buildData(this.tableConfig.data);
        this.init();
      }
    });
  }

  buildData(data) {
    data.map(item => {
      if (item.children && item.children.length > 0) {
        item.children.map(ele => {
          ele.parentId = item.key;
          ele.parentTitle = item.title;
        });
        this.buildData(item.children);
      }
    });
  }

  /**
   * 校验
   */
  initForm() {
    this.validateForm = this.fb.group({
      parentId: [this.departInfos.parentId, []],
      name: [this.departInfos.name, [Validators.required]],
      leader: [this.departInfos.leader, []],
      leaderList: [this.departInfos.leaderList, []],
      telphone: [this.departInfos.telphone, []],
      fax: [this.departInfos.fax, []]
    });
  }

  init() {
    // @ts-ignore
    this.treeGrid = new TreeGrid(this.tableConfig);
    this.treeGrid.show();
    const that = this;
    $('#deptRef').on('click', '.operateBtn', function() {
      const rowData = JSON.parse($(this).attr('data-row'));
      if ($(this).html() === '编辑') {
        that.editDept(rowData);
      } else if ($(this).html() === '添加子机构') {
        that.addDeptOwn(rowData);
      } else if ($(this).html() === '删除') {
        that.deleteDept(rowData);
      }
    });
  }

  /**
   * 新增
   */
  clickAdd() {
    this.departInfos = new DepartInfo();
    this.placeholderText = '默认顶级部门';
    this.initForm();
    this.getTeachList();
    this.isVisible = true;
  }

  /**
   * 点击编辑
   */
  editDept(data) {
    this.getTeachList();
    this.departInfos = new DepartInfo();
    this.departInfos.id = data.key;
    this.departInfos.name = data.title;
    this.departInfos.telphone = data.telphone;
    this.departInfos.fax = data.fax;
    this.departInfos.parentId = data.parentId ? data.parentId : '0';
    this.placeholderText = data.parentTitle ? data.parentTitle : '默认顶级部门';
    if (data.leaderId !== 'undefined' && data.leaderId !== null) {
      this.departInfos.leaderId = data.leaderId.split(',');
    }
    if (data.leaderIdStr) {
      this.departInfos.leaderList = data.leaderIdStr.split(',');
    }
    this.isVisible = true;
  }

  /**
   * 点击添加子机构
   */
  addDeptOwn(data) {
    this.getTeachList();
    this.departInfos = new DepartInfo();
    this.departInfos.parentId = data.key;
    this.isVisible = true;
    this.initForm();
  }

  /**
   * 点击删除
   */
  deleteDept(data) {
    this.http.delete({
      id: data.key
    }).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.pageList();
      }
    });
  }

  /**
   * 获取教师
   */
  getTeachList() {
    this.http.getTeachList().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.headTeacherList = res.datas;
      }
    });
  }

  /**
   * 提交保存
   */
  submit() {
    this.departInfos.leaderId = this.departInfos.leaderId + '';
    if (!this.departInfos.parentId) {
      this.departInfos.parentId = '0';
      this.departInfos.id ? this.dealEditSub() : this.dealAddSub();
    } else {
      this.departInfos.id ? this.dealEditSub() : this.dealAddSub();
    }
  }

  /**
   * 编辑提交
   */
  dealEditSub(): void {
    const arr = [];
    (this.departInfos.leaderList || []).map(item => {
      arr.push({
        leaderId: item
      });
    });
    this.http.update({
      ...this.departInfos,
      leaderList: arr
    }).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.isVisible = false;
        this.pageList();
      }
    });
  }

  /**
   * 新增提交
   */
  dealAddSub(): void {
    const arr = [];
    (this.departInfos.leaderList || []).map(item => {
      arr.push({
        leaderId: item
      });
    });
    this.http.submit({
      ...this.departInfos,
      leaderList: arr
    }).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.isVisible = false;
        this.pageList();
      }
    });
  }

}
/**
 * 新增部门实体
 */
export class DepartInfo {
  fax?: string;
  id?: string;
  leader?: string;
  leaderId?: any;
  // principal: string;
  leaderList: any;
  name?: string;
  telphone?: string;
  parentId?: string;
}
